package com.nordstrom;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.HasParentFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.tags.InputTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.dao.DBUtil;
import com.dao.DealBean;
import com.mongodb.MongoException;
import com.util.CategoryMapping;

public class NordStromHtmlParser {
	public  void testParser(String filePath, String url) throws UnknownHostException, MongoException {  
        
		DealBean nordStromBean = new DealBean();

		try {  
			String skuId = "";
			
            Parser parser = new Parser(filePath);  
            
            
            nordStromBean.setBuy_url(url);

            parser.setEncoding("UTF-8");  
            
            NodeFilter skuIdNodeFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("id", "skuSelector"));
            
            NodeList skuIdNodeList = parser.extractAllNodesThatMatch(skuIdNodeFilter); 
            
            if (skuIdNodeList != null && skuIdNodeList.size() > 0) {  

                Node skuIdNode = skuIdNodeList.elementAt(0);  

                skuId = ((Tag)skuIdNode).getAttribute("styleId");  

                nordStromBean.setSku_id(skuId);

            }
            
            parser.reset();
            
            NodeFilter imageUrlFilter = new NodeClassFilter(ImageTag.class);
            
            NodeFilter imageUrlNodeFilter = new HasParentFilter(new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class", "fashion-photo-wrapper")));

            NodeList imageUrlTagList = parser.extractAllNodesThatMatch(imageUrlFilter);
            
            NodeList imageUrlNodeList = imageUrlTagList.extractAllNodesThatMatch(imageUrlNodeFilter);
            
            if (imageUrlNodeList != null && imageUrlNodeList.size() > 0) {  

                ImageTag imageUrlNode = (ImageTag) imageUrlNodeList.elementAt(0);
                
                String imageUrl = imageUrlNode.getImageURL();
                
                try {
					saveFile(imageUrl, skuId);
				} catch (Exception e) {
					e.printStackTrace();
				}

				nordStromBean.setImage_url(imageUrl);  

            }
            
            parser.reset();
            
            NodeFilter productNameNodeFilter = new TagNameFilter("h1");
            
            NodeList productNameNodeList = parser.extractAllNodesThatMatch(productNameNodeFilter);
             
              if (productNameNodeList != null && productNameNodeList.size() > 0) {  

                  Node productNameNode = productNameNodeList.elementAt(0);  

                  String productName = productNameNode.toPlainTextString().trim();  

                  nordStromBean.setProduct_name(productName); 

              }  

            parser.reset(); 
            
            NodeFilter salePriceNodeFilter = new AndFilter(new TagNameFilter("span"),new HasAttributeFilter("class", "price regular"));
            
            NodeList salePriceNodeList = parser.extractAllNodesThatMatch(salePriceNodeFilter);
            
            if (salePriceNodeList != null && salePriceNodeList.size() > 0) {  
          	  
                Node salePriceNode = salePriceNodeList.elementAt(0);  

                String salePrice = salePriceNode.toPlainTextString().trim();
                
                if(salePrice.contains("Was:")){
                	
                	nordStromBean.setOriginal_price(salePrice);
                }
                
                else{

                nordStromBean.setSale_price(salePrice);
                
                }

            } 
            
            parser.reset(); 
            
            NodeFilter originalPriceNodeFilter = new AndFilter(new TagNameFilter("span"),new HasAttributeFilter("class", "price sale"));
            
            NodeList originalPriceNodeList = parser.extractAllNodesThatMatch(originalPriceNodeFilter);
            
            if (originalPriceNodeList != null && originalPriceNodeList.size() > 0) {  
          	  
                Node originalPriceNode = originalPriceNodeList.elementAt(0);  

                String originalPrice = originalPriceNode.toPlainTextString().trim();
                
                if(originalPrice.contains("Now:")){
                	
                	nordStromBean.setSale_price(originalPrice);
                }
                
                else{

                nordStromBean.setOriginal_price(originalPrice);
                
                }

            } 
            
            parser.reset(); 
            
            NodeFilter modelNodeFilter = new AndFilter(new TagNameFilter("li"),new HasAttributeFilter("class", "itemNumber"));
            
            NodeList modelIdList = parser.extractAllNodesThatMatch(modelNodeFilter);
            
            if (modelIdList != null && modelIdList.size() > 0) { 
            
            Parser modelParser = new Parser(modelIdList.elementAt(0).toHtml());
            
            NodeFilter modelIdNodeFilter = new TagNameFilter("span");
            
            NodeList modelIdNodeList = modelParser.extractAllNodesThatMatch(modelIdNodeFilter);
            
            if (modelIdNodeList != null && modelIdNodeList.size() > 0) { 
            	
            	Node modelIdNode = modelIdNodeList.elementAt(0);
            	
            	String modelId = modelIdNode.toPlainTextString().trim();
            	
            	nordStromBean.setModel_id(modelId);
            
            }
            
            }
            
            parser.reset();
            
            NodeFilter brandFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class", "brand-content"));
            
            NodeList brandList = parser.extractAllNodesThatMatch(brandFilter);
            
            if (brandList != null && brandList.size() > 0) {
            
            Parser brandParser = new Parser(brandList.elementAt(0).toHtml());
            
            NodeFilter brandNodeFilter = new TagNameFilter("a");
            
            NodeList brandNodeList = brandParser.extractAllNodesThatMatch(brandNodeFilter);
            
            if (brandNodeList != null && brandNodeList.size() > 0) { 
            	
            	Node brandNode = brandNodeList.elementAt(0);
            	
            	String brand = brandNode.toPlainTextString().trim();
            	
            	nordStromBean.setBrand(brand);
            
            }
            
            }
            
            parser.reset();
            
            NodeFilter categoryFilter = new AndFilter(new TagNameFilter("ul"),new HasAttributeFilter("class", "breadcrumbs"));
            
            NodeList categoryList = parser.extractAllNodesThatMatch(categoryFilter);
            
            if (categoryList != null && categoryList.size() > 0) { 
            
            Parser categoryParser = new Parser(categoryList.elementAt(0).toHtml());
            
            NodeFilter categoryNodeFilter = new TagNameFilter("li");
            
            NodeList categoryNodeList = categoryParser.extractAllNodesThatMatch(categoryNodeFilter);
            
            if (categoryNodeList != null && categoryNodeList.size() > 0) { 
            	
            	Node categoryNode = categoryNodeList.elementAt(2);
            	
            	String category1 =  CategoryMapping.getType1(categoryNode.toPlainTextString().trim());
            	
            	nordStromBean.setCategory1(category1);
            
            }
            
            }
            
            parser.reset();
            
            NodeFilter productDescriptionFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("id", "productdetails"));
            
            NodeList productDescriptionList = parser.extractAllNodesThatMatch(productDescriptionFilter);
            
            if (productDescriptionList != null && productDescriptionList.size() > 0) { 
            	
            	String productDescription = productDescriptionList.elementAt(0).toPlainTextString().trim();
                
                nordStromBean.setProduct_description(productDescription);
            	
            }
            
            String endsTime = "";
            
            nordStromBean.setEnds_time(endsTime);
            
            String souceSite = "NordStrom";
            
            nordStromBean.setSouce_site(souceSite);
            
          }catch(ParserException e){  

            e.printStackTrace();  

          } 
          
          
          DBUtil db = new DBUtil();
          
          if(nordStromBean.getSku_id()!=null){
          
          db.save(nordStromBean);
          }

  }  
	 private static void saveFile(String imgString, String productId) throws Exception {
		  	URL url;
		  	File outFile;
		  	OutputStream os = null;
		  	InputStream is = null;
				try {
					url = new URL(imgString);
					outFile = new File("C:/nordstrom/img/"+productId+".jpg");
					os = new FileOutputStream(outFile);
					is = url.openStream();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				byte[] buff = new byte[1024];
				while(true) {
					int readed = is.read(buff);
					if(readed == -1) {
						break;
					}
					byte[] temp = new byte[readed];
					System.arraycopy(buff, 0, temp, 0, readed);
					os.write(temp);
				}
				is.close(); 
		      os.close();
			}

    

 
}
